<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录 - 巴士运营管理系统</title>
    <style>
        /* Reset and base styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        /* Manga/Comic Style Elements */
        .container {
            width: 100%;
            max-width: 400px;
        }
        
        .manga-panel {
            background-color: white;
            border: 4px solid black;
            padding: 30px;
            position: relative;
            overflow: hidden;
            box-shadow: 8px 8px 0 #000;
        }
        
        /* Corner decorations */
        .manga-panel::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 60px;
            height: 60px;
            background-color: black;
            clip-path: polygon(100% 0, 0 0, 100% 100%);
        }
        
        .manga-panel::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 60px;
            height: 60px;
            background-color: black;
            clip-path: polygon(0 100%, 100% 100%, 0 0);
        }
        
        .manga-title {
            font-size: 28px;
            font-weight: 900;
            text-align: center;
            margin-bottom: 25px;
            letter-spacing: 2px;
            text-shadow: 2px 2px 0 #000;
            -webkit-text-stroke: 1px black;
            color: white;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .manga-label {
            display: block;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .manga-input {
            width: 100%;
            padding: 10px 12px;
            background-color: white;
            border: 2px solid black;
            font-size: 16px;
        }
        
        .manga-input:focus {
            outline: none;
            box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.3);
        }
        
        .manga-button {
            width: 100%;
            padding: 12px 20px;
            background-color: black;
            color: white;
            font-weight: bold;
            font-size: 18px;
            border: none;
            cursor: pointer;
            transition: transform 0.2s;
            box-shadow: 4px 4px 0 #666;
        }
        
        .manga-button:hover {
            transform: scale(1.05);
        }
        
        .manga-button:active {
            transform: scale(0.95);
            box-shadow: 2px 2px 0 #666;
        }
        
        .manga-text {
            text-align: center;
            margin-top: 20px;
            font-weight: 500;
        }
        
        .manga-text a {
            color: black;
            text-decoration: underline;
            font-weight: bold;
        }
        
        .manga-text a:hover {
            color: #333;
        }
        
        .manga-speech-bubble {
            padding: 12px;
            background-color: white;
            border: 2px solid black;
            position: relative;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .manga-speech-bubble::after {
            content: '';
            position: absolute;
            width: 15px;
            height: 15px;
            background-color: white;
            border-right: 2px solid black;
            border-bottom: 2px solid black;
            bottom: -9px;
            left: 20px;
            transform: rotate(45deg);
        }
        
        .manga-error {
            background-image: repeating-linear-gradient(45deg, transparent, transparent 5px, rgba(0,0,0,0.1) 5px, rgba(0,0,0,0.1) 10px);
        }
        
        .manga-speech-bubble p {
            flex-grow: 1;
        }
        
        .close-button {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            font-weight: bold;
        }
        
        .hidden {
            display: none;
        }
        
        .icon {
            margin-right: 8px;
            width: 20px;
            height: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="manga-panel">
            <h2 class="manga-title">用户登录</h2>
            
            <div id="login-message" class="manga-speech-bubble manga-error hidden">
                <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="10"></circle>
                    <line x1="12" y1="8" x2="12" y2="12"></line>
                    <line x1="12" y1="16" x2="12.01" y2="16"></line>
                </svg>
                <p id="message-text"></p>
                <button class="close-button" onclick="closeMessage()">×</button>
            </div>
            
            <form id="login-form">
                <div class="form-group">
                    <label for="username" class="manga-label">帐号：</label>
                    <input type="email" 
                           id="username" 
                           name="username" 
                           required 
                           placeholder="请输入邮箱"
                           class="manga-input">
                </div>
                
                <div class="form-group">
                    <label for="password" class="manga-label">密码：</label>
                    <input type="password" 
                           id="password" 
                           name="password" 
                           required 
                           placeholder="请输入密码"
                           class="manga-input">
                </div>
                
                <button type="submit" class="manga-button" id="submit-button">登录</button>
            </form>
            
            <p class="manga-text">
                没有账号？<a href="/register">立即注册</a>
            </p>
        </div>
    </div>

    <script>
        // 确保页面加载时获取CSRF Token
        document.addEventListener('DOMContentLoaded', () => {
            fetch('/api/get-csrf/', { 
                credentials: 'include' 
            }).catch(console.error);
        });

        const loginForm = document.getElementById('login-form');
        const messageContainer = document.getElementById('login-message');
        const messageText = document.getElementById('message-text');
        const submitButton = document.getElementById('submit-button');
        
        function showMessage(message, isError = true) {
            messageText.textContent = message;
            messageContainer.classList.remove('hidden');
            messageContainer.classList.toggle('manga-error', isError);
        }
        
        function closeMessage() {
            messageContainer.classList.add('hidden');
        }

        // 增强版Cookie获取函数
        function getCookie(name) {
            return document.cookie
                .split('; ')
                .find(row => row.startsWith(name + '='))
                ?.split('=')[1] || '';
        }

        loginForm.addEventListener('submit', async function(event) {
            event.preventDefault();
            
            const formData = {
                email: document.getElementById('username').value.trim(),
                password: document.getElementById('password').value
            };

            // 基础验证
            if (!formData.email || !formData.password) {
                showMessage('请输入邮箱和密码');
                return;
            }

            submitButton.disabled = true;
            submitButton.textContent = '登录中...';
            
            try {
                const csrfToken = getCookie('csrftoken');
                if (!csrfToken) {
                    throw new Error('系统安全校验失败，请刷新页面');
                }

                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrfToken
                    },
                    credentials: 'include',  // 重要：包含cookie
                    body: JSON.stringify(formData)
                });

                // 先检查HTTP状态码
                if (!response.ok) {
                    const error = await response.json().catch(() => ({}));
                    throw new Error(error.detail || `登录失败 (HTTP ${response.status})`);
                }

                const data = await response.json();
                
                // 存储Token并跳转
                localStorage.setItem('access_token', data.access_token);
                
                const roleMap = {
                    admin: '/admin/',
                    dispatcher: '/dashboard/',
                    user: '/passenger/schedule_lookup/'
                };
                
                window.location.href = roleMap[data.role?.toLowerCase()] || '/passenger/schedule_lookup/';
                
            } catch (error) {
                console.error('登录错误:', error);
                showMessage(error.message || '网络连接错误，请稍后重试');
            } finally {
                submitButton.disabled = false;
                submitButton.textContent = '登录';
            }
        });
    </script>
</body>
</html>